package com.hss.common.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 作者：黄赛赛 on 2015/11/17 11:24
 *
 * @version V1.0
 * @Description: ${todo}()
 */
public class GetImgUtil {

    // **********************上传图片*************************8
    public static final int REQUEST_CAMERA_CODE = 50000;
    public static final int REQUEST_ALBUM_CODE = 50001;
    public static final int REQUEST_PHOTO_CROP = 50002;
    /*
	 * 剪切图片
	 */
    public static void crop(Activity activity, Uri uri, int requestCode) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        activity.startActivityForResult(intent, requestCode);
    }

    /*
        * 剪切图片
        */
    public static void crop(Fragment fragment,Uri uri,int requestCode) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        fragment.startActivityForResult(intent, requestCode);
    }

    /**
     *
     * @ 功能 跳转到相机 @ 作者 2014-5-25 / 黄赛赛
     */
    public static Uri requestCamera(Fragment fragment,int requestCode) {

        Uri uri =null;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
        // *****************图片上传*********************
        // if (cameraImagePath == null)
        // cameraImagePath = CommonUtil.getCurProjectDir(this) + "image.jpg";
        // Uri imageUri = Uri.fromFile(new File(cameraImagePath));

        // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        uri = getCameraUri(fragment.getActivity());
         intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        // 直接使用，没有缩小

        fragment.startActivityForResult(intent, requestCode); // 用户点击了从相机获取
        return uri;
    }

    public static Uri requestCamera(Activity activity,int requestCode) {
        Uri uri =null;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
        // *****************图片上传*********************
        // if (cameraImagePath == null)
        // cameraImagePath = CommonUtil.getCurProjectDir(this) + "image.jpg";
        // Uri imageUri = Uri.fromFile(new File(cameraImagePath));

        // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        uri = getCameraUri(activity);
         intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        // 直接使用，没有缩小

        activity.startActivityForResult(intent, requestCode); // 用户点击了从相机获取
        return uri;
    }


    public static Uri getCameraUri(Context context) {
        Uri imagePath = null;
        String status = Environment.getExternalStorageState();
        SimpleDateFormat fomater = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String timeString = fomater.format(new Date(time));
        ContentValues values = new ContentValues(3);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, timeString);
        values.put(MediaStore.Images.Media.DATE_TAKEN, time);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            imagePath = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            imagePath = context.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
        }

        return imagePath;
    }

    /**
     *
     * @ 功能 跳转到相册 @ 作者 2014-5-25 / 黄赛赛
     */
    public static  void requestAlbum(Activity activity,int requestCode) {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK);
        openAlbumIntent.setType("image/*");
        openAlbumIntent.putExtra("return-data", true); // 有返回值
        activity.startActivityForResult(openAlbumIntent, requestCode);

    }

    /**
     *
     * @ 功能 跳转到相册 @ 作者 2014-5-25 / 黄赛赛
     */
    public static void requestAlbum(Fragment fragment,int requestCode) {

        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK);
        openAlbumIntent.setType("image/*");
        openAlbumIntent.putExtra("return-data", true); // 有返回值
        fragment.startActivityForResult(openAlbumIntent, requestCode);

    }

   /* case REQUEST_CAMERA_CODE:
            if (resultCode != Activity.RESULT_OK)
            return;
    if (data.getData() == null) {
        Bundle bundle = data.getExtras();
        Bitmap bmp = (Bitmap) bundle.get("data");
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(
                getActivity().getContentResolver(), bmp, null, null));
        crop(uri);
        if (bmp != null && bmp.isRecycled()) {
            bmp.recycle();
            bmp = null;
        }
    } else {
        crop(data.getData());
    }

    break;
    case REQUEST_ALBUM_CODE:
            if (resultCode != Activity.RESULT_OK)
            return;
    // 照片的原始资源地址
    crop(data.getData());
    break;

    case REQUEST_PHOTO_CUT:
            if (data != null) {
        Bitmap bmp = data.getExtras().getParcelable("data");
        imgFile = FileUtils.getSDRoot() + File.separator
                + TimeTools.getSystemSeconds() + ".jpg";
        if (saveBitmapAsFile(bmp, imgFile)) {
            // Picasso p = Picasso.with(PersonalSetActivity.this);
            // p.load(imgFile).tag(civ_personset_head);
            modifyHeadImg();
        } else {
            ToastUtil.showToast(getActivity(), "获取图片出错", false);
        }
        if (bmp != null && !bmp.isRecycled()) {
            bmp.recycle();
        }
    }
    break;




    */

    /**
     *
     * @Title: saveBitmapAsFile
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param fileName
     * @param @return 设定文件
     * @return boolean 返回类型 @ 作者　2014-9-26 / 黄赛赛
     * @throws
     */
    public static boolean saveBitmapAsFile(Bitmap bmp, String fileName) {
        boolean flag = false;
        File newfile = new File(fileName);
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(newfile);
            flag = bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bmp != null) {
                bmp = null;
            }
        }
        return flag;
    }
}
